package com.ailanyin.admin.controller;

import com.ailanyin.admin.service.SysLogService;
import com.ailanyin.common.result.AjaxResult;
import com.ailanyin.common.result.CommonPage;
import com.ailanyin.common.utils.ExcelUtil;
import com.ailanyin.model.SysLog;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/28 0028 下午 14:45
 */
@RestController
@RequestMapping("/system/log")
@Api(tags = "后台日志管理")
public class SysLogController {

    @Autowired
    private SysLogService sysLogService;

    @GetMapping("/list")
    @ApiOperation(value = "分页获取日志列表")
    @PreAuthorize("hasAuthority('system:log:list')")
    public CommonPage list(SysLog sysLog,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysLog> list = sysLogService.list(sysLog);
        return CommonPage.restPage(list);
    }

    @DeleteMapping("/clean")
    @ApiOperation(value = "清空日志")
    @PreAuthorize("hasAuthority('system:log:remove')")
    public AjaxResult cleanLog() {
        sysLogService.cleanLog();
        return AjaxResult.success();
    }

    @DeleteMapping("/remove")
    @ApiOperation(value = "批量删除日志")
    @PreAuthorize("hasAuthority('system:log:remove')")
    public AjaxResult removeLog(@RequestBody List<String> logIds) {
        sysLogService.removeLog(logIds);
        return AjaxResult.success();
    }

    @GetMapping("/export")
    @PreAuthorize("hasAuthority('system:log:export')")
    @ApiOperation(value = "导出日志")
    public AjaxResult export(SysLog sysLog) {
        List<SysLog> list = sysLogService.list(sysLog);
        try {
            return AjaxResult.success(ExcelUtil.exportExcel(list, "系统日志表", "系统日志", SysLog.class, "系统日志"));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
}
